<template>
  <div>
    <component :is="remote" v-if="remote" v-model="name" @childClick="childClick"/>
  </div>
</template>

<script setup>
import {loadModule} from "vue3-sfc-loader/dist/vue3-sfc-loader"
import * as Vue from 'vue'
import {onMounted, defineAsyncComponent, ref, watchEffect} from "vue"


let remote = ref()
let name = ref("李四")
let url = "http://localhost:3000/getVue3Str"


onMounted(() => {
  load(url)
})

watchEffect(() => {
  console.log(name.value)
})

const childClick = (newVal) => {
  console.log("子组件点击事件", newVal)
}

// 加载远程文件
const load = async (url) => {
  let res = await fetch(url).then(res => res.json());

  const options = {
    moduleCache: {
      vue: Vue
    },
    async getFile() {
      return res.fileStr
    },
    addStyle(textContent) {
      const style = Object.assign(document.createElement('style'), {textContent})
      const ref = document.head.getElementsByTagName('style')[0] || null
      document.head.insertBefore(style, ref)
    },
  };

  // 加载远程组件
  remote.value = defineAsyncComponent(() => loadModule(res.fileName || "loader.vue", options))
}
</script>

<style></style>
